import { useEffect, useState } from 'react';
import { cityTreeListStore } from '@/business/store/city/city';
import { Picker } from '@tarojs/components';

interface CityPickerProps {
  onRegionChange?: (value: string) => void;
  onRegionIdChange?: (id: string) => void;
  children?: (regionText: string) => React.ReactNode;
  value?: string; // 传入的省市区 ID 路径，如 "provinceId,cityId,districtId"
}

export default function CityPicker(props: CityPickerProps) {
  // 获取地区数据
  const cityTreeList = cityTreeListStore((state: { cityTreeList: any; }) => state.cityTreeList);

  // 选择的地区文本
  const [regionText, setRegionText] = useState('');

  // 三级联动相关状态
  const [regionMultiArray, setRegionMultiArray] = useState<[string[], string[], string[]]>([[], [], []]);
  const [regionMultiIndex, setRegionMultiIndex] = useState<[number, number, number]>([0, 0, 0]);

  // 根据 ID 路径找到索引的辅助函数
  const findIndicesByIds = (ids: string[]): [number, number, number] => {
    const [provinceId, cityId, districtId] = ids;
    const provinceIdx = cityTreeList.findIndex((p: any) => p.id === provinceId);
    if (provinceIdx === -1) return [0, 0, 0];
    const cities = cityTreeList[provinceIdx]?.children || [];
    const cityIdx = cities.findIndex((c: any) => c.id === cityId);
    if (cityIdx === -1) return [provinceIdx, 0, 0];
    const districts = cities[cityIdx]?.children || [];
    const districtIdx = districts.findIndex((d: any) => d.id === districtId);
    return [provinceIdx, cityIdx, districtIdx === -1 ? 0 : districtIdx];
  };

  useEffect(() => {
    if (cityTreeList.length > 0) {
      let provinces = cityTreeList.map((p: any) => p.name);
      let cities: string[] = [];
      let districts: string[] = [];
      let indices: [number, number, number] = [0, 0, 0];
      let text = '';

      if (props.value) {
        const ids = props.value.split(',');
        indices = findIndicesByIds(ids);
        const [provinceIdx, cityIdx, districtIdx] = indices;
        cities = cityTreeList[provinceIdx]?.children?.map((c: any) => c.name) || [];
        districts = cityTreeList[provinceIdx]?.children?.[cityIdx]?.children?.map((d: any) => d.name) || [];
        const province = cityTreeList[provinceIdx];
        const city = province?.children?.[cityIdx];
        const district = city?.children?.[districtIdx];
        text = [province?.name, city?.name, district?.name].filter(Boolean).join(' ');
      } else {
        cities = cityTreeList[0]?.children?.map((c: any) => c.name) || [];
        districts = cityTreeList[0]?.children?.[0]?.children?.map((d: any) => d.name) || [];
      }

      setRegionMultiArray([provinces, cities, districts]);
      setRegionMultiIndex(indices);
      setRegionText(text);
    }
  }, [cityTreeList, props.value]);

  useEffect(() => {
    if (cityTreeList.length > 0) {
      const provinces = cityTreeList.map((p: any) => p.name);
      const cities = cityTreeList[0]?.children?.map((c: any) => c.name) || [];
      const districts = cityTreeList[0]?.children?.[0]?.children?.map((d: any) => d.name) || [];
      setRegionMultiArray([provinces, cities, districts]);
    }
  }, [cityTreeList]);

  // Picker 柱变化时，动态更新下级选项
  const handleRegionColumnChange = (e: any) => {
    const column = e.detail.column;
    const value = e.detail.value;
    let newMultiIndex = [...regionMultiIndex] as [number, number, number];
    newMultiIndex[column] = value;
    if (column === 0) {
      // 省变化，更新市和区
      const cities = cityTreeList[value]?.children?.map((c: any) => c.name) || [];
      const districts = cityTreeList[value]?.children?.[0]?.children?.map((d: any) => d.name) || [];
      setRegionMultiArray([
        regionMultiArray[0],
        cities,
        districts,
      ]);
      newMultiIndex[1] = 0;
      newMultiIndex[2] = 0;
    } else if (column === 1) {
      // 市变化，更新区
      const provinceIdx = newMultiIndex[0];
      const citiesArr = cityTreeList[provinceIdx]?.children || [];
      const districts = citiesArr[value]?.children?.map((d: any) => d.name) || [];
      setRegionMultiArray([
        regionMultiArray[0],
        regionMultiArray[1],
        districts,
      ]);
      newMultiIndex[2] = 0;
    }
    setRegionMultiIndex(newMultiIndex);
  };

  // Picker 选中后，展示地区名称并回调拼接好的省市区
  const handleRegionChange = (e: any) => {
    const [provinceIdx, cityIdx, districtIdx] = e.detail.value;
    setRegionMultiIndex([provinceIdx, cityIdx, districtIdx]);
    const province = cityTreeList[provinceIdx];
    const city = province?.children?.[cityIdx];
    const district = city?.children?.[districtIdx];
    const text = [province?.name, city?.name, district?.name].filter(Boolean).join(' ');
    setRegionText(text);
    props.onRegionChange?.(text);
    const ids = [province, city, district].map(item => item?.name !== '全部' ? item?.id : null).filter(Boolean);
    let id = ids.join(',');
    if (id) {
      const parts = id.split(',');
      if (parts.length === 1) {
        id = parts.slice(0).join(',');
      } else if (parts.length === 2) {
        id = parts.slice(1).join(',');
      } else if (parts.length === 3) {
        id = parts.slice(2).join(',');
      }
    }
    console
      .log(id, 'id')
    props.onRegionIdChange?.(id);
  };

  return (
    <Picker
      mode='multiSelector'
      range={regionMultiArray}
      value={regionMultiIndex}
      onChange={handleRegionChange}
      onColumnChange={handleRegionColumnChange}
    >
      {props.children ? props.children(regionText) : null}
    </Picker>
  );
}
